﻿using System;
using System.Windows.Forms;

public class CalendarCell : DataGridViewTextBoxCell
{
    public CalendarCell()
        : base()
    {
        this.Style.Format = "d";// Use the short date format. 
    }
    public static DateTime CellMaxDate { get; set; }
    public static DateTime CellMinDate { get; set; }
    public DateTime MinDate { get; set; }
    public DateTime MaxDate { get; set; }
    public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)   // Set the value of the editing control to the current cell value.
    {
        base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);

        var ctl = DataGridView.EditingControl as CalendarEditingControl;
        ctl.MinDate = DateTimePicker.MinimumDateTime;
        ctl.MaxDate = DateTimePicker.MaximumDateTime;
        ctl.MinDate = MinDate;
        ctl.MaxDate = MaxDate;
        if (this.Value == null)// Use the default row value when Value property is null.
        {
            ctl.EditingControlFormattedValue = ctl.Value = (DateTime)this.DefaultNewRowValue;
        }
        else
        {
            var value = DateTime.Parse(this.Value.ToString());
            if (value.Date <= MinDate.Date)
            {
                value = MinDate;
            }
            else if (value.Date >= MaxDate.Date)
            {
                value = MaxDate;
            }
            ctl.EditingControlFormattedValue = ctl.Value = value;
        }
    }
    public override Type EditType // Return the type of the editing control that CalendarCell uses.       
    {
        get { return typeof(CalendarEditingControl); }
    }
    public override Type ValueType// Return the type of the value that CalendarCell contains.
    {
        get { return typeof(DateTime); }
    }
    public override object DefaultNewRowValue// Use the current date and time as the default value.
    {
        get
        {
            if (DateTime.Now.Date < CellMinDate.Date)
                return CellMinDate.Date;
            if (DateTime.Now.Date > CellMaxDate.Date)
                return CellMaxDate.Date;
            return DateTime.Now;

        }
    }
}